package jiyici;

import handler.DataInvalidException;

import java.util.ArrayList;

import models.ServerBaseModel;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonNode;

import util.ModelUtil;

public class Client2ServerSyncItem {

    public String tableName;
    
    private ArrayList<ServerBaseModel> models;
    
    public ArrayList<ServerBaseModel> getModels() {
        return models;
    }
    
    public void fromJson(JsonNode json) throws DataInvalidException {
        tableName = json.findPath("tableName").getTextValue();
        if (StringUtils.isBlank(tableName))
            throw new DataInvalidException();
        JsonNode rows = json.findPath("rows");
        if (rows == null || !rows.isArray())
            throw new DataInvalidException();
        int size = rows.size();
        models = new ArrayList<ServerBaseModel>(size + 1);
        for (int i = 0; i < size; i++) {
            JsonNode row = rows.get(i);
            ServerBaseModel model = ModelUtil.createModel(tableName);
            if (model != null) {
                model.fromJson(row);
                models.add(model);
            }
        }
    }
}
